import re
from myapp.utils.connection import POOL


def terminalToJson(kw, mid=''):
    # conn = pymysql.connect(host='localhost', user='root', passwd='password', db='zhifou', port=3306, charset='utf8')
    conn = POOL.connection()
    cur = conn.cursor()
    if mid == '':
        sql = "SELECT source FROM {}_findson".format(kw)
    else:
        # 根据根节点筛选
        sql = "SELECT source FROM {}_findson WHERE rootknot = {}".format(
            kw, mid)
    cur.execute(sql)
    result = {}
    data = cur.fetchall()

    iphone = re.compile("iPhone")
    rongyao = re.compile("荣耀")
    xiaomi = re.compile("小米")
    oppo = re.compile("OPPO")
    yijia = re.compile("OnePlus")
    huawei = re.compile("华为")
    vivo = re.compile("vivo")
    xiaomi = re.compile("米")
    ipad = re.compile("iPad")
    sanxing = re.compile("三星")
    weibo = re.compile("weibo.com")
    liulanqi = re.compile("浏览器")
    meizu = re.compile("魅族")

    for sub_text in data:
        # print(sub_text)
        source = sub_text[0]
        terminal = "其他"
        if iphone.search(source):
            terminal = "iPhone"
        if rongyao.search(source) or huawei.search(source):
            terminal = "华为"
        if xiaomi.search(source):
            terminal = "小米"
        if oppo.search(source):
            terminal = "OPPO"
        if vivo.search(source):
            terminal = "vivo"
        if ipad.search(source):
            terminal = "iPad"
        if yijia.search(source):
            terminal = "一加"
        if sanxing.search(source):
            terminal = "三星"
        if weibo.search(source) or liulanqi.search(source):
            terminal = "PC"
        if meizu.search(source):
            terminal = "魅族"

        if terminal in result.keys():
            result[terminal] = result[terminal] + 1
        else:
            result[terminal] = 1
    print(result)
    cur.close()
    # conn.close()
    result_list = []
    for key in result.keys():
        result_list.append({"value": result[key], "name": key})
    # final = {"data": [{"value": result['iPhone'], "name": "iPhone"},
    #                   {"value": result['PC'], 'name': 'PC'},
    #                   {'value': result['其他'], 'name': '其他'},
    #                   {'value': result['华为'], 'name': '华为'},
    #                   {'value': result['OPPO'], 'name': 'OPPO'},
    #                   {'value': result['三星'], 'name': '三星'},
    #                   {'value': result['小米'], 'name':'小米'},
    #                   {'value': result['iPad'], 'name': 'iPad'},
    #                   {'value': result['vivo'], 'name': 'vivo'},
    #                   {'value': result['一加'], 'name': '一加'},
    #                   {'value': result['魅族'], 'name': '魅族'}
    #                   ]}
    final = {"data": result_list}
    return (final)
